let async = require('async');
let xml2js = require('xml2js');
let _ = require('underscore');
require('../../init/properties');
// connect mongodb
require('../../models');
// redis
require('../../init/initRedis');
// properties
require('../../init/properties');
let sms = require('../../utils/sms');
let phoneUtils = require('../../utils/phoneUtils');

let errinfo = require('../../errinfo');
let responseJsonUtils = require('../../utils/responseJsonUtils');

// let userId = process.argv[process.argv.length - 3];
let smsRecordId = process.argv[process.argv.length - 2];
let message = process.argv[process.argv.length - 1];
let pos = 0; // remember position of current send
// console.log('smsRecordId -- ' + smsRecordId);
let smsRecord; // store sms Record
let sendingArray = []; // store current sending array
let repeatCheck = {}; // check cellphone duplicate

// send to master process
// process.send({err: undefined});

SmsRecord.findById(smsRecordId)
    .exec()
    .then(function (smsRecordResult) {
        if (!smsRecordResult) {
            mongooseConnection.close();
            process.exit(0);
            return;
        }
        storeSmsRecord(smsRecordResult);
        async.eachSeries(smsRecordResult.readyMembers, function (member, cb) {
            async.setImmediate(function () {
                pos++;
                // add to sending array
                if (member.cellphone && phoneUtils.validateMobileNumber(member.cellphone)) {
                    if (!repeatCheck[member.cellphone]) {
                        repeatCheck[member.cellphone] = true;
                        sendingArray.push(member);
                    } else {
                        // console.log('number duplicate -- ', member.cellphone);
                    }
                }
                if (sendingArray.length < SMS.emay.maxSize && pos !== smsRecordResult.readyMembers.length) {
                    cb();
                } else {
                    if (sendingArray.length === 0) {
                        cb();
                        return;
                    }
                    // send sms
                    let cellphoneArray = Array.from(sendingArray, function (item) {
                        return item.cellphone;
                    });
                    console.log('cellphoneArray size -- ', cellphoneArray.length);
                    sms.emaySendWithSignature(cellphoneArray, smsRecordResult.signature, message, null, null, function (error, response, body) {
                        // console.log('response body -- ' + body);
                        if (error === 1) {
                            cb(responseJsonUtils.json(errinfo.sms.cellphoneEmpty));
                            return;
                        } else {
                            cb();
                        }
                        // if (!error && response.statusCode == 200) {
                        //     xml2js.parseString(body, function (err, result) {
                        //         console.log('result -- ', JSON.stringify(result));
                        //         if (err) {
                        //             cb();
                        //             return;
                        //         }
                        //         if (!result) {
                        //             sendingArray.length = 0;
                        //             cb();
                        //             return;
                        //         }
                        //         if (result.response.error[0] == 0) {
                        //             sendingArray.length = 0;
                        //             cb();
                        //         } else {
                        //             // error
                        //             // cb(responseJsonUtils.json(JSON.stringify(result)));
                        //             sendingArray.length = 0;
                        //             cb();
                        //         }
                        //     });
                        // } else {
                        //     cb(error);
                        // }
                    });
                }
            });

        }, function (err) {
            if (err) {
                // save sms record
                updateSmsRecord(smsRecordResult, sendingArray, pos, false, function updateSmsRecordEnd() {
                    // err
                    console.log('err -- ', err.message);
                    mongooseConnection.close();
                    process.exit(0);
                });
            } else {
                // save sms record
                updateSmsRecord(smsRecordResult, sendingArray, pos, true, function updateSmsRecordEnd() {
                    console.log('success -- ' + pos);
                    mongooseConnection.close();
                    process.exit(0);
                });
            }
        });
        // start send sms
    })
    .catch(function (err) {
        updateSmsRecord(smsRecordResult, sendingArray, pos, false, function updateSmsRecordEnd() {
            console.log('err -- ', err.message);
            mongooseConnection.close();
            process.exit(0);
        });
    });

function updateSmsRecord(smsRecordResult, sendingArray, pos, isSuccess, cb) {
    if (!smsRecordResult) {
        cb();
        return;
    }

    let splicePos = pos;
    if (!isSuccess) {
        // error occur, not delete sendingArray
        if (sendingArray) {
            splicePos = splicePos - sendingArray.length;
        }
    }
    let completedMembers = smsRecordResult.readyMembers.splice(0, splicePos);
    if (isSuccess) {
        smsRecordResult.status = 'success';
    } else {
        smsRecordResult.status = 'failure';
    }

    smsRecordResult.completeTime = new Date();
    smsRecordResult.completedMembers = completedMembers;
    smsRecordResult.save(function (err, recordResult) {
        cb();
    });
}
function storeSmsRecord(record) {
    if (!record) {
        return;
    }
    smsRecord = record;
}